﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;

namespace HYTextTool
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdTextEdit : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string messages, ElementSet elements)
		{
			Document document = cmdData.Application.ActiveUIDocument.Document;
			Selection selection = cmdData.Application.ActiveUIDocument.Selection;
			XYZ ptInsert = null;
			Element element = null;
			TextTool textTool = new TextTool(cmdData);
			List<Text> textListByGroup;
			do
			{
				Reference reference = null;
				try
				{
					reference = selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, "请选择需要编辑的文本");
				}
				catch
				{
					return Autodesk.Revit.UI.Result.Succeeded;
				}
				element = document.GetElement(reference);
				textListByGroup = textTool.GetTextListByGroup(element);
			}
			while (textListByGroup == null);
			ptInsert = textListByGroup[0].Position;
			TextToolForm textToolForm = new TextToolForm();
			textToolForm.EditText(textListByGroup);
			bool flag;
			while ((flag = (DialogResult.OK == textToolForm.ShowDialog())) && textToolForm.m_pickInScreen)
			{
				List<Text> list = new List<Text>();
				try
				{
					for (;;)
					{
						Reference reference2 = selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, "请选择文本(Esc完成选择)");
						Element element2 = document.GetElement(reference2);
						List<Text> textList = textTool.GetTextList(element2);
						if (textList != null)
						{
							list.AddRange(textList);
						}
					}
				}
				catch
				{
					textToolForm.InsertText(list);
				}
			}
			if (!flag)
			{
				return Autodesk.Revit.UI.Result.Succeeded;
			}
			try
			{
				List<Row> rows = textTool.TransformSectionToRow(textToolForm.m_sections);
				List<Page> pages = textTool.TransformRowToPage(rows);
				textTool.SetTextLocation(ptInsert, pages);
				Transaction transaction = new Transaction(document, "DrawText");
				transaction.Start();
				try
				{
					document.Delete(element.Id);
					textTool.DrawText(ptInsert, pages, textToolForm.m_scripts, textToolForm.m_aligns, textToolForm.m_length);
					transaction.Commit();
				}
				catch
				{
					transaction.RollBack();
					return Autodesk.Revit.UI.Result.Failed;
				}
			}
			catch
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}
	}
}
